package com.gcloud.mesh.framework.core.web.handle;

import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import lombok.Data;

@ConfigurationProperties(prefix = "error", ignoreUnknownFields = false)
@PropertySource(value = {"classpath:errorcode.properties"}, encoding = "UTF-8", ignoreResourceNotFound = true)
@Component
@Data
public class ErrorCodeMapper {

	private Map<String, String> maps;

    public String getErrorMsg(String errorCode) {
        if (errorCode == null || maps == null) {
            return null;
        }
        String realCode = errorCode;
        String[] params = null;
        String tmpStr = null;
        if (errorCode.indexOf("::") > -1) {
            String[] arr = errorCode.split("::");
            realCode = arr[0];
            tmpStr = arr[1];
            params = tmpStr.split("$$");
        }
        String msg = "";
        if(tmpStr != null) {
        	msg = tmpStr;
        }else {
            List<String> errorMsg = Lists.newArrayList();
            for (String s : errorCode.split(",")) {
                if(maps.get(s)!=null)errorMsg.add(maps.get(s));
            }
        	msg = String.join(" , ",errorMsg);
        }
        if (msg.indexOf("%s") > -1) {
            msg = String.format(msg, params);
        }
        return msg;
    }
}
